Tailwind CSS

Width and Height


Tailwind CSS provides utility classes for setting the width and height of your elements, allowing for responsive control over their dimensions.

 

Width

Tailwind offers classes with the prefix w- for width control.

 

1. Percentage-based widths: 

These are often used for responsive layouts. Classes with the prefix w- followed by a percentage value (e.g., w-1/2, w-3/4) define the element's width as a percentage of its parent container.

 

2. Fixed-width classes:

For setting a specific pixel width, use classes like w-px (1 pixel), w-2 (2 pixels), and so on, based on Tailwind's spacing scale.

 

3. Screen-based widths:

Control width based on screen sizes using responsive prefixes like md:, lg:, etc. For example, md:w-1/2 lg:w-1/3 makes the element half-width on medium screens and one-third width on large screens and above.

 

Height

Like width, Tailwind offers classes with the prefix h- for height control:

 

1. Percentage-based heights:

Use classes like h-1/2, h-full (100% height of the parent) for responsive layouts.

 

2. Fixed-height classes:

Set a specific pixel height with classes like h-px, h-10, etc.

 

3. Viewport height:

Apply h-vh or h-lvh for viewport height or largest viewport height, respectively.

 

4. Responsive heights

Use screen size prefixes (e.g., sm:h-20 md:h-32) to adjust height based on screen size.

 

Examples:

<div class="container">
 <div class="w-1/2 bg-red-200 p-4"> This element is half the width of its container. </div>
 <div class="w-full h-20 bg-blue-200 p-4"> This element spans the full width and has a fixed height of 20 pixels. </div>
 <div class="md:w-3/4 lg:h-vh bg-green-200 p-4"> This element becomes 3/4 width on medium screens and takes up the full viewport height on large screens and above. </div>
</div>


Note:

You can use negative width or height values (e.g., -h-3 and -w-2) to achieve overlapping elements or create spacing effects.